/**
 * Copyright (c) 2016 Lenovo Group
 * All Rights Reserved.
 * 
 * Project Name:app-gateway
 * Create Time: 2016年1月18日 下午6:27:16
 */
package com.lenovo.lmrp.server.appgateway.spi;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;

import com.lenovo.lmrp.api.model.view.LoginData;
import com.lenovo.lmrp.server.appgateway.AppSession;
import com.lenovo.lmrp.server.appgateway.util.AppCache;
import com.lenovo.sdc.framework.annotation.RestInterceptor;
import com.lenovo.sdc.framework.cache.CacheItem;
import com.lenovo.sdc.framework.rest.BaseRestFilter;
import com.lenovo.sdc.framework.util.Tuple;

/**
 * @author zhangzhenga
 *
 */
@RestInterceptor
public class AppGatewayFilter extends BaseRestFilter {

    private static String[] ignorePaths = { "/app/v1/\\w+/oauth2/token", 
                                            "/app/v1/\\w+/oauth2/logout", 
                                            "/app/v1/\\w+/oauth2/retoken",
                                            "/favicon.ico",
                                            "/app/v1/image/\\w.+",
                                            "/app/v1/page/\\w.+",
                                            "/app/measurer/\\w.+"};

    @Override
    public Set<Pattern> getIgnorePaths() {
        Set<Pattern> patterns = new HashSet<Pattern>(ignorePaths.length);
        for (String path : ignorePaths) {
            Pattern pattern = Pattern.compile(path);
            patterns.add(pattern);
        }
        return patterns;
    }

    @Override
    public Tuple.Pair<String, Boolean> hasAuthenticated(String token) {

        CacheItem<AppSession> cache = AppCache.getClient().get(AppSession.class,token);
        AppSession session = cache.getValue();
        //检查用户token是否已经过期
        if (session == null || session.tokenExpired()) {
        	String user = Objects.isNull(session) ? token : session.getLoginData().getLoginname();
            return Tuple.makePair(user, false);
        }
        else {
            LoginData loginData = session.getLoginData();
            return Tuple.makePair(loginData.getLoginname(), true);
        }
    }
}
